#include "base/assert.hpp"
#include "event/loop.hpp"
#include "network/buffered_fd.hpp"

#include <memory>

using namespace ibox::event;
using namespace ibox::network;

/**
 * 测试方法：
 * 在事件循环开始之前，一次性塞入10个 "123456789\0"
 * 并注册一个定时器, 每20ms发送1个 "123456789\0", 共分10次进行
 * 定时2秒后检查, 最后总共应该收到20个 "1234567879\0"
 */
int main() {
    auto loop = Loop();
    int fds[2] = {0};
    expect(pipe(fds) == 0);
    int recv_count = 0;

    // 创建接收的BufferedFd
    auto read_buffd = std::make_unique<BufferedFd>(loop.ptr());
    Fd read_fd{fds[0]};
    read_buffd->initialize(read_fd);
    read_buffd->set_receive_callback(
        [&recv_count](Buffer &buff) {
            while (buff.readable_size() >= 10) {
                char read_data[10];
                buff.fetch(read_data, 10);
                expect(strcmp(read_data, "123456789") == 0);
                recv_count++;
            }
        },
        10);
    read_buffd->enable();

    // 创建发送的BufferedFd
    auto write_buffd = std::make_unique<BufferedFd>(loop.ptr());
    Fd write_fd{fds[1]};
    write_buffd->initialize(write_fd);
    write_buffd->set_send_complete_callback([]() {});
    write_buffd->enable();

    // 创建定时发送的定时器, 每20ms一次, 执行10次
    int send_times = 0;
    TimerEvent timer_event{loop.ptr(), 20ms, Event::Mode::Forever};
    timer_event.set_callback(
        [&] {
            ++send_times;
            write_buffd->send("123456789", 10);

            if (send_times == 10) {
                timer_event.disable();
            }
        }
    );
    timer_event.enable();

    // 在run() 前发送10个数据
    for (int i = 0; i < 10; ++i) {
        write_buffd->send("123456789", 10);
    }

    loop.stop(2s);
    loop.run();
    expect(recv_count == 20);
}
